package com.mycompany.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.mycompany.entity.Bill;
import com.mycompany.repository.BillDao;

@Repository
public class BillDaoImpl implements BillDao {
	
	private EntityManager em;
	String sqlQuery="";
	

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public void persist(Bill bill) {
		em.persist(bill);
	}

	@Override
	public void merge(Bill bill) {
		em.merge(bill);
	}

	@Override
	public void remove(Bill bill) {
		bill.setActiveFlg(false);
		em.merge(bill);
	}

	@Override
	public Bill findById(Integer billId) {
		sqlQuery = "select x from Bill x where x.billId= :billId and x.activeFlg = 1";
		return (Bill) em.createQuery(sqlQuery).setParameter("billId", billId).getSingleResult();
	}

	@Override
	public Bill find(Bill bill) {
		sqlQuery = "select x from Bill x where x.billId= :billId and x.activeFlg = 1";
		return (Bill) em.createQuery(sqlQuery).setParameter("billId", bill.getBillId()).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Bill> findAll() {
		sqlQuery = "select x from Bill x where x.activeFlg = 1 ORDER BY x.billId DESC ";
        return em.createQuery(sqlQuery).getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Bill> findListByCodition(Bill bill) {
		sqlQuery = "select * from Bill where 1=1   and  activeFlg = 1 ";
		
		if(bill.getName() != null ){
			sqlQuery = sqlQuery+" AND name like '%"+bill.getName()+"%' ";
		}
		
		sqlQuery = sqlQuery+ " ORDER BY billId DESC "; 
        return em.createNativeQuery(sqlQuery,Bill.class).getResultList();
	}
}
